package com.lovo.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.web.bean.UserAddressBean;
import com.lovo.web.mapper.IUserAddressMapper;
import com.lovo.web.service.IUserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserAddressServiceImpl implements IUserAddressService {
    @Autowired
    IUserAddressMapper IUserAddressMapper;

    @Override
    public void add(UserAddressBean userAddress) {
        QueryWrapper<UserAddressBean> qw = new QueryWrapper<>();
        qw.eq("fk_userName", userAddress.getUserName());
        List<UserAddressBean> userAddressBeans = IUserAddressMapper.selectList(qw);
        if (userAddressBeans.size() < 1) {
            userAddress.setIsDefault(0);
        }
        IUserAddressMapper.insert(userAddress);

    }

    @Override
    public void del(long addressId) {
        IUserAddressMapper.deleteById(addressId);

    }

    @Override
    public void update(UserAddressBean userAddress) {
        IUserAddressMapper.updateById(userAddress);
    }

    @Override
    public void updateAddress(long addressId) {
        UserAddressBean addressBean = IUserAddressMapper.selectById(addressId);
        QueryWrapper<UserAddressBean> qw = new QueryWrapper<>();
        qw.eq("fk_userName", addressBean.getUserName());
        qw.eq("a_isDefault", 0);
        UserAddressBean beans = IUserAddressMapper.selectOne(qw);
        beans.setIsDefault(1);
        IUserAddressMapper.updateById(beans);

        addressBean.setIsDefault(0);
        IUserAddressMapper.updateById(addressBean);


    }

    @Override
    public List<UserAddressBean> findAll(String userName) {
        List<UserAddressBean> all = IUserAddressMapper.findAll(userName);
        return all;
    }


}
